package org.phoenixframework.gateway.filter;

import com.google.gson.JsonObject;
import io.jsonwebtoken.*;
import org.phoenixframework.common.tools.Constants;
import org.phoenixframework.gateway.config.IgnoreUrlsConfig;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/4 0:08
 * Description:
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    private IgnoreUrlsConfig ignoreUrlsConfig;

    private boolean checkToken(String token, JsonObject message) {
        try {
            Jwts.parser().setSigningKey(Constants.JWT_SIGNING_KEY).parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            message.addProperty("success", false);
            message.addProperty("code", 50014);
            message.addProperty("data", "JWT is a Claims JWT and the Claims has an expiration time");
            return Boolean.FALSE;
        } catch (UnsupportedJwtException e) {
            message.addProperty("success", false);
            message.addProperty("code", 50015);
            message.addProperty("data", "token argument does not represent an Claims JWS");
            return Boolean.FALSE;
        } catch (MalformedJwtException e) {
            message.addProperty("success", false);
            message.addProperty("code", 50016);
            message.addProperty("data", "string is not a valid JWS");
            return Boolean.FALSE;
        } catch (SignatureException e) {
            message.addProperty("success", false);
            message.addProperty("code", 50017);
            message.addProperty("data", "JWS signature validation fails");
            return Boolean.FALSE;
        } catch (IllegalArgumentException e) {
            message.addProperty("success", false);
            message.addProperty("code", 50018);
            message.addProperty("data", "string is null or empty or only whitespace");
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        JsonObject message = new JsonObject();
        String path = request.getURI().getPath();
        // 白名单路径
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (antPathMatcher.match(ignoreUrl, path)) {
                return chain.filter(exchange);
            }
        }

        if (!antPathMatcher.match("/phoenix/api/rbac/**/login/**", path)) {
            List<String> tokenList = request.getHeaders().get("token");
            if (null == tokenList || tokenList.size() == 0) {
                message.addProperty("success", false);
                message.addProperty("code", 28004);
                message.addProperty("data", "token为空，鉴权失败！！！");
                return out(response, message);
            } else {
                if (!checkToken(tokenList.get(0), message)) {
                    return out(response, message);
                }
                return chain.filter(exchange);
            }
        }
        // 内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            message.addProperty("success", false);
            message.addProperty("code", 28004);
            message.addProperty("data", "内部服务接口，不允许外部访问！！！");
            return out(response, message);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, JsonObject message) {
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
